import axios from 'axios'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // set common request headers
    configCommonHeaders(config)
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // 获取正常数据，xxxx是与后端约定的成功code
    if (res.statuscode && res.statuscode != 200) {
      return Promise.reject(res)
    }
    return res
  },
  error => {
    // 获取状态码
    const status = error.response ? error.response.status : ''
    // 获取错误信息
    let errorMsg = error.message
    const errorData = error.response ? error.response.data : {}
    if (status === 500) {
      if (process.env.NODE_ENV === 'development') {
        console.log('response with error : ' + errorMsg) // for debug
      }
      errorMsg = '服务器开小差了~'
    }

    return Promise.reject(errorData)
  }
)

function configCommonHeaders(config) {
  config.headers.post['Content-Type'] = 'application/json'
  config.headers.post['Cache-Control'] = 'no-cache'
  config.headers.get['Access-Control-Allow-Origin'] = '*'

  if (store.state.user.token) {
    config.headers.Systoken = `${store.state.user.token}`
  }
  return config
}

export default service
